import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Row, Col, Input, Button, Table, Card, message, Icon, Pagination } from 'antd';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import styles from './Home.less';
import PageLoading from '@/components/PageLoading';

const IntroduceRow = React.lazy(() => import('./IntroduceRow'));
const ProportionSales = React.lazy(() => import('./ProportionSales'));

const columns = [
  {
    title: '热度变化',
    dataIndex: 'hotChange',
    key: 'hotChange',
    sorter: true,
    render: (text, row) => {
      if (row.yesterdayCount >= row.beforYesterdayCount) {
        return <Icon type="arrow-up" style={{ color: 'green' }} />;
      }
      return <Icon type="arrow-down" style={{ color: 'red' }} />;
    },
    align: 'center',
  },
  {
    title: '知识点标准问',
    dataIndex: 'question',
    key: 'question',
    defaultSortOrder: 'descend',
    sorter: (a, b) => a.question.length - b.question.length,
    align: 'center',
  },
  {
    title: '命中次数',
    dataIndex: 'yesterdayCount',
    key: 'yesterdayCount',
    defaultSortOrder: 'descend',
    sorter: (a, b) => a.yesterdayCount - b.yesterdayCount,
    align: 'center',
  },
  {
    title: '环比变化',
    dataIndex: 'momChange',
    key: 'momChange',
    render: (text, row) => {
      if (row.yesterdayCount >= row.beforYesterdayCount) {
        if(row.beforYesterdayCount ==0 ){
          return (
            <span style={{ marginRight: 4 }}>
              {((row.yesterdayCount ))}%
              <Icon type="caret-up" style={{ color: 'green' }} />
            </span>
          );
        }else{
          return (
            <span style={{ marginRight: 4 }}>
              {((row.yesterdayCount / row.beforYesterdayCount))}%
              <Icon type="caret-up" style={{ color: 'green' }} />
            </span>
          );
        }

      }
      return (
        <span style={{ marginRight: 4 }}>
          {((row.beforYesterdayCount / row.yesterdayCount) * 100).toFixed(2)}%
          <Icon type="caret-down" style={{ color: 'green' }} />
        </span>
      );
    },
    align: 'center',
    defaultSortOrder: 'descend',
    sorter: (a, b) => a.momChange - b.momChange,
  },
];

@connect(({ home, loading }) => ({
  home,
  loading: loading.effects['home/fetch'],
}))
class Home extends Component {
  state = {
    salesType: 'all',
    page: 1,
    homeObj:{},
    items:[],
    total:0,
    loading:true
  };

  componentDidMount() {
    const that = this;
    const { dispatch ,currentUser} = this.props;
    const searchKey = that.state.searchKey;
    const page = that.state.page;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'home/fetch',
        payload: { robotId: currentUser.robotId },
        callback:(res)=> {
          console.log(1)
          this.setState({
            homeObj:res
          })
        }
      }).then(()=>{
          dispatch({
            type: 'home/fakeTableDataList',
            payload: { robotId: currentUser.robotId , key: searchKey, page: page, limit: 10 },
            callback:(res)=> {
              console.log(2)
              this.setState({
                items:res.items,
                total:res.total,
                loading:false
              })
            }
          });
      })
    });
  }

  handleChangeSalesType = e => {
    this.setState({
      salesType: e.target.value,
    });
  };

  // 昨日热点问题搜索排序点击操作
  selectDate = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
  };

  // 昨日热点问题搜索
  searchData = () => {
    const that = this;
    const searchKey = that.state.searchKey;
    const page = this.state.page;
    const { dispatch ,currentUser} = this.props;
    dispatch({
      type: 'home/fakeTableDataList',
      payload: { robotId: currentUser.robotId, key: searchKey, page: page, limit: 10 },
      callback:(res)=> {
        this.setState({
          items:res.items,
          total:res.total,
          loading:false
        })
      }
    });
  };

  // 搜索框动态输入
  inputVal(val) {
    this.setState({
      searchKey: val.target.value,
    });
  }

  // 翻页
  fanye(e) {
    this.setState({
      page: e,
    },()=>{
      this.searchData()
    });
  }

  render() {
    const {  items,total,homeObj ,loading} = this.state;
    const { home } = this.props;
    const {
      visitorTup,
      chatCountTup,
      matchRateTup,
      unknownCountTup,
      hitCountTup,
    } = home;
    let questionTotalNumber =0 ;
    if(JSON.stringify(hitCountTup) !== "{}"){
      for(let i of hitCountTup){
        questionTotalNumber = questionTotalNumber+i.y
      }
      if(questionTotalNumber == 0){
        hitCountTup.push({ x: "暂无数据", y: 1 })
      }
    }
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow loading={loading} visitData={home} />
        </Suspense>
        <div className={styles.twoColLayout}>
          <Row gutter={24}>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <ProportionSales
                  loading={loading}
                  salesPieData={hitCountTup}
                  handleChangeSalesType={this.handleChangeSalesType}
                />
              </Suspense>
            </Col>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Suspense fallback={null}>
                <Card
                  loading={loading}
                  className={styles.salesCard}
                  bordered={false}
                  title={
                    <FormattedMessage
                      id="app.home.hot-questions-yesterday"
                    />
                  }
                  bodyStyle={{ padding: 24 }}
                >
                  <Row>
                    <Col xs={8}>
                      <Input
                        placeholder="请输入搜索内容"
                        onPressEnter={value => this.searchData(value)}
                        onChange={e => this.inputVal(e)}
                        allowClear
                      />
                    </Col>
                    <Col xs={8}>
                      <Button
                        type="primary"
                        htmlType="button"
                        style={{ marginLeft: '10px' }}
                        onClick={this.searchData}
                      >
                        搜索
                      </Button>
                    </Col>
                  </Row>
                  <Table
                    dataSource={items}
                    rowKey="key"
                    onChange={this.selectDate}
                    columns={columns}
                    style={{ marginTop: '10px' }}
                    bordered
                    size="small"
                    pagination={false}
                    algin="center"
                  />
                  <Pagination
                    total={parseInt(total)}
                    onChange={e =>this.fanye(e)}
                    style={{ float: 'right', marginTop: '10px' }}
                  />
                </Card>
              </Suspense>
            </Col>
          </Row>
        </div>
      </GridContent>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Home);
